import ajax from "./ajax";
import { startGlobalTimer } from './timer'
const checkJump = async function(){
   //胜任
  const anotherType =wx.getStorageSync('anotherType')||''
  //心理
  const mentalId =wx.getStorageSync('mentalId')||''
  //认知
  const bussId =wx.getStorageSync('bussId')||''
   //当前试卷
  const paperId = wx.getStorageSync('paperId')

   const userInfo = wx.getStorageSync('userInfo');
   //如果用户数据没有清除所有缓存，不做跳转
   if(!userInfo){
      wx.clearStorageSync();
      return
   }
   try {
    let getType = await ajax.getMethod('small/app/paper/list/'+ userInfo.idcard+'/'+userInfo.unitId);
    if(checkClear(getType,anotherType,mentalId,bussId)){
      return
    }
   } catch (error) {

   }
    //如果当前考试是认知
   if(paperId==bussId){
     const questionInfo =wx.getStorageSync('questionInfo')
     //如果找不到缓存认知试题详情。清除缓存不做跳转
     if(!questionInfo){
      wx.clearStorageSync();
      return
     }
     let questionNumber = questionInfo.questionNumber
     const questionList = questionInfo.questionList
     //如果找不到缓存认知试题详情。清除缓存不做跳转
     if(!questionList||questionList.length==0){
      wx.clearStorageSync();
      return
     }
     let answerBaseArray  = wx.getStorageSync('answerRecords')
     //如果未作答清除缓存不跳转
     if(!answerBaseArray||answerBaseArray.length==0){
      wx.clearStorageSync();
      return
     }
     const length = questionList.length
     if(questionNumber>length){
        questionNumber=length-1
     }
     const set =new Set()
     questionList.forEach((element,index) => {
        if(index>=questionNumber){
          set.add(element.typeCode)
        }
     })
     answerBaseArray =answerBaseArray.filter(item=>!set.has(item.classify))
     wx.setStorageSync('answerRecords',answerBaseArray)
    //获取新的认知试题详情
    // try {
    //   const res = await ajax.getMethod('small/app/paper/info/' + bussId + '/' +userInfo.idcard+ '/' +userInfo.unitId)
    //   if(res&&res.data){
    //     const paperQuestionTypes = res.data?.paperQuestionTypes??''
    //     if(paperQuestionTypes){
    //       questionInfo.questionList = paperQuestionTypes
    //       wx.setStorageSync('questionInfo',questionInfo)
    //     }
    //   }
    // } catch (error) {

    // }
     navigateByDesc(questionNumber);
     startGlobalTimer();//开始计时
   }else{
     //如果不是认知直接跳转到心理或者胜任页面
    wx.reLaunch({
      url: '/pages/topic-another/topic-another?id='+paperId
    })
   }

   // 截屏
   wx.onUserCaptureScreen(() => {
    // 立即弹出警告
    wx.showModal({
      title: "禁止截屏",
      content: "同学，您的截屏动作已被后台记录，再次截屏将会自动取消成绩！",
      showCancel: false
    });
    const userInfo = wx.getStorageSync('userInfo');
    const paperId = wx.getStorageSync('paperId');
    const testType = wx.getStorageSync('testType');
    console.log(testType)
    let idCard = '';
    let userName = '';

    if (userInfo) {
      idCard = userInfo.idcard;
      userName = userInfo.name;
    }

    // 提交截图者的身份信息
    ajax.postMethod('small/app/add/screenCapture', {
      userName:userName,
      idCard: idCard,
      answerWork: userInfo.unitId,
      testId:paperId,
      testType:testType
    }).then(res => {
      console.log('截图信息提交成功', res)
    }).catch(err => {
      console.error('截图信息提交失败', err);
    });
  });

}
/**校验缓存数据是否以请求试卷一致。如果不一致清除所有缓存不跳转 */
function checkClear(getType,oldAnotherType,oldMentalId,oldBussId){
  //如果获取试卷失败所有缓存，不做跳转
  if(getType.code !== 200){
    wx.clearStorageSync()
    return true
  }
  const type = getType.data.find(item => item.ptype == 1)
  const anotherType = getType.data.find(item => item.ptype === 2)
  const mentalInfo = getType.data.find(item => item.ptype === 3)

  const anotherTypeId = anotherType?.paperId??'0'
  const mentalId = mentalInfo?.paperId??'0'
  const bussId = type?.paperId??'0'

  if(oldAnotherType===anotherTypeId&&oldMentalId===mentalId&&oldBussId===bussId){
     return false
  }else{
    wx.clearStorageSync();
    return true
  }
}

const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return `${[year, month, day].map(formatNumber).join('/')} ${[hour, minute, second].map(formatNumber).join(':')}`
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : `0${n}`
}

// 查看大图的通用方法
const previewImage = function (current, urls) {
  // 如果只传入一个图片URL，则将其转换为数组
  if (typeof current === 'string') {
    urls = urls || [current];
    // 如果没有提供urls，则使用current作为唯一图片
    if (!Array.isArray(urls)) {
      urls = [current];
    }
  }

  // 如果current是数组，则默认显示第一张图片
  if (Array.isArray(current)) {
    urls = current;
    current = current[0];
  }

  wx.previewImage({
    current: current, // 当前显示图片的http链接
    urls: urls // 需要预览的图片http链接列表
  });
};
// 题型
const topicType = [
  {
    typeCode:'RQ06',
    typeUrl:'../topic-location/topic-location'
  },
  {
    typeCode:'RQ08',
    typeUrl:'../topic-arrow/topic-arrow'
  },
  {
    typeCode:'RQ09',
    typeUrl:'../topic-number/topic-number'
  },
  {
    typeCode:'RQ14',
    typeUrl:'../topic-equation/topic-equation'
  },
  {
    typeCode:'RQ15',
    typeUrl:'../topic-pattern/topic-pattern'
  },
  {
    typeCode:'RQ16',
    typeUrl:'../topic-picture/topic-picture'
  },
  {
    typeCode:'RQ17',
    typeUrl:'../topic-model/topic-model'
  },
  {
    typeCode:'RQ20',
    typeUrl:'../topic-color/topic-color'
  },
  {
    typeCode:'RQ22',
    typeUrl:'../topic-scale/topic-scale'
  },
  {
    typeCode:'RQ23',
    typeUrl:'../topic-scale/topic-scale'
  },
  {
    typeCode:'RQ26',
    typeUrl:'../topic-sequence-number/topic-sequence-number'
  },
  {
    typeCode:'RQ28',
    typeUrl:'../topic-time/topic-time'
  },
  {
    typeCode:'RQ30',
    typeUrl:'../topic-square/topic-square'
  },
  {
    typeCode:'RQ32',
    typeUrl:'../topic-decision/topic-decision'
  },
  {
    typeCode:'RQ33',
    typeUrl:'../topic-decision/topic-decision'
  },
  {
    typeCode:'RQ34',
    typeUrl:'../topic-decision/topic-decision'
  },
  {
    typeCode:'RQ35',
    typeUrl:'../topic-decision/topic-decision'
  },
  {
    typeCode:'RQ36',
    typeUrl:'../topic-decision/topic-decision'
  },
  {
    typeCode:'RQ37',
    typeUrl:'../topic-decision/topic-decision'
  },
  {
    typeCode:'RQ38',
    typeUrl:'../topic-decision/topic-decision'
  },
  {
    typeCode:'RQ41',
    typeUrl:'../topic-attention/topic-attention'
  }
];
const navigateByDesc = function (questionNumber) {
  const questionList = wx.getStorageSync('questionInfo').questionList;
  preLoadImg(questionNumber + 1,0)
  if (questionList.length > questionNumber) {
    let number = wx.getStorageSync('publicNumber') || 0;
    number++;
    wx.setStorageSync('publicNumber',number)
    const topicContent = questionList[questionNumber];
    const describe = JSON.parse(topicContent.describe);
    const desc = describe[0].content;
    // 如果题型有描述，跳转到描述页面，如果没有描述直接跳转到对应题目页面
    if (desc) {
      const validTypeCodes = ['RQ08', 'RQ20', 'RQ41'];
      const { typeCode } = topicContent;
      if (validTypeCodes.includes(typeCode)) {
        wx.reLaunch({
          url: '../topic-desc/topic-desc?isExercise=true', // 添加参数
        });
      } else {
        wx.reLaunch({
          url: '../topic-desc/topic-desc',
        });
      }
    } else {
      navigateByTypeCode(questionNumber);
    }
  }else{
    wx.reLaunch({
      url: "../topic-end/topic-end"
    });
  }
};
const navigateByTypeCode = function (questionNumber) {
  const questionList = wx.getStorageSync('questionInfo').questionList;
  if (questionList.length > questionNumber) {
    const item = questionList[questionNumber];
    const { typeCode } = item;
    const matchItem = topicType.find(t => t.typeCode === typeCode);
    if (matchItem && matchItem.typeUrl) {
      wx.reLaunch({
        url: matchItem.typeUrl
      });
    }
  }
};
const getData = function (questionIndex) {
  const questionInfo = wx.getStorageSync('questionInfo');
  const questionList = questionInfo.questionList || [];
  if (!questionList[questionIndex]) {
    return {
      count: 0,
      topicContent: []
    };
  }
  const count = questionList[questionIndex].questionNumber;
  const topicContent = questionList[questionIndex].lqs || [];
  return {
    count,
    topicContent
  };
};

async function replaceAsync(str, regex,preImgs,aftherFcu) {
  const promises = []
  str.replace(regex, (_match,src) => {
    if (!src.startsWith('http')) {
        src = base_url+src
    }
    let src2 =  preImgs.find(item => item.url===src)?.path??''
    //src = src2||src
    const promise = pathToBase64(src,src2)
    promises.push(promise)    //存入到数组
  })
  const data = await Promise.all(promises)
  return str.replace(regex, () => {
     return aftherFcu(data.shift())
  })
}
const pathToBase64 =(url,type)=>{
  const isIos =  checkPlatform()
  let filePath = url+'?x-oss-process=image/format,webp' 
  if(isIos){
    filePath = url+'?x-oss-process=image/format,jpg' 
  }
   return new Promise((resolve) => {
     if(!type){
      resolve (filePath)
      return
     }
     try {
      wx.getFileSystemManager().readFile({
        filePath: type,
        encoding: 'base64',
        complete: fileRes => {
           if (fileRes.errMsg == 'readFile:ok') {
            let dataUrl
            if(isIos){
              dataUrl = `data:image/jpg;base64,${fileRes.data}`;
            }else{
              dataUrl = `data:image/webp;base64,${fileRes.data}`;
            }
            resolve(dataUrl);
           } else {
            resolve (filePath)
           }
         }
       });
     } catch (error) {
       console.error('转化base64失败 '+error)
       resolve (filePath)
     }
   })
}
const preLoadImg=(questionNumber,num)=>{
  const questionInfo = wx.getStorageSync('questionInfo');
  const questionList = questionInfo.questionList || [];
  const length=  questionList.length
  if(questionNumber>=length){
    return
  }
  const testInfo =  questionList[questionNumber]
  if(!testInfo){
    return
  }
  const typeCode = testInfo.typeCode ||''
  const lqs = testInfo.lqs
  if(!lqs||lqs.length<=0){
    return
  }
  const length2 = lqs.length
  if(num>=length2){
    return
  }
  const allImgs = lqs[num]?.allImgs??[]
  if(!allImgs||allImgs.length<=0){
    return
  }
  allImgs.forEach(item=>{
    const preImgs = wx.getStorageSync('preImgs')||[];
    if(preImgs.find(img => img.url===item)){
       return
    }
     const isIos =  checkPlatform()
     let newPath = ''
     if(isIos){
       if(typeCode == 'RQ30'){
         newPath =item
       }else{
         newPath =item+'?x-oss-process=image/format,jpg'
       }
     }else{
      newPath = item+'?x-oss-process=image/format,webp'
     }
    wx.getImageInfo({
      src: newPath,
      success: (res) => {
        if(!res.path){
          return
        }
        const preImgs = wx.getStorageSync('preImgs')||[];
        preImgs.push({
          url: item,
          path: res.path
        })
        wx.setStorageSync('preImgs', preImgs);
      }
    });
  })
}
// 使用示例
 function checkPlatform() {
  try {
    const deviceInfo = wx.getDeviceInfo()
    let system = deviceInfo?.system??''
    system = system.toLocaleLowerCase()
    if(system.indexOf('ios')>=0){
      return true
    }
    return false;
  } catch (error) {
    return true
  }
}
const base_url = "https://pcces.ceair.com";
// const base_url = "http://122.114.130.217";
// const another_url = "http://122.114.130.217";
module.exports = {
  formatTime,
  navigateByTypeCode,
  getData,
  base_url,
  navigateByDesc,
  previewImage,
  checkJump,
  preLoadImg,
  pathToBase64,
  replaceAsync,
  checkPlatform
}
